package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 传统写法：
     * @Autowired
     * private CategoryDao categoryDao;
     *
     * 但是Impl类已经继承了ServiceImpl类，其中CategoryDao是泛型，ServiceImpl中有一个baseMapper对象，
     * 所以在类中可以直接用baseMapper 就是categoryDao对象。
     */


    /**
     * @param params
     * @return
     */

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        //没有查询条件，就是查询所有
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> level1 = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(menu -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        //


        return level1;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 1、检查当前删除的菜单是否被别的地方引用，如果引用了，不能删

        //逻辑删除


        //物理删除
        baseMapper.deleteBatchIds(asList);
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return children;
    }

    //[2,25,225]
    @Override
    public Long[] findCategoryPath(long categoryId) {
        List<Long> paths = new ArrayList<>();
        List<Long> res = findParentPath(categoryId, paths);
        return res.toArray(new Long[res.size()]);

    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    @Override
    public List<CategoryEntity> getLevel1Categories() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    public Map<String, List<Catalog2VO>> getCatalogJSON() {
        //查出所有1级分类
        List<CategoryEntity> level1Categories = getLevel1Categories();
        //封装数据
        Map<String, List<Catalog2VO>> listMap = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    //每一个的一级分类 查到这个一级分类的二级分类
                    List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
                    //封装上面的结果
                    List<Catalog2VO> catalog2VOS = null;
                    if (categoryEntities != null) {
                        catalog2VOS = categoryEntities.stream().map(l2 -> {
                            //二级分类
                            Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //找当前二级分类的三级分类 封装成vo
                            List<CategoryEntity> catalog3Entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                            if (catalog3Entities != null && catalog3Entities.size() > 0) {
                                List<Catalog2VO.Catalog3VO> catalog3VOS = catalog3Entities.stream().map(l3 -> {
                                    Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catalog3VO;

                                }).collect(Collectors.toList());
                                catalog2VO.setCatalog3List(catalog3VOS);

                            }


                            return catalog2VO;
                        }).collect(Collectors.toList());


                    }
                    return catalog2VOS;
                }));

        return listMap;
    }

    private List<Long> findParentPath(Long categoryId, List<Long> paths) {
        //父
        CategoryEntity category = this.getById(categoryId);
        Long pid = category.getParentCid();
        paths.add(0, categoryId);

        //base case
        if (pid == 0) {
            return paths;
        } else {
            return findParentPath(pid, paths);
        }
        /*
        paths.add(catelogId);
        CategoryEntity category = this.getById(categoryId);
        if(category.getParentId!=0){
            findParentPath(byId.getParentCid,paths);
        }
        return paths;

        //之后还要逆序


         */

    }

}